<?php
/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2018/5/8
 * Time: 16:32
 */

namespace App\Abstracts\Entities;

use Hilaoyu\Utils\UtilArr;
use Hilaoyu\Utils\UtilHtml;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Contracts\Support\Arrayable;
use Hilaoyu\LaravelExtend\Entity;


abstract class AbstractEntityCatalogs extends Entity
{

    public function getGroup($key = ''){
        $key = trim($key);

        $model = UtilSupport::makeClassSingle(static::classNameModelMain());

        return $key ? $model->getAllowedGroupName($key) : $model->getAllowedGroups();

    }

    public function buildGroupOptions($selected=[],$add_title=false){


        $options = [];

        foreach ($this->getGroup() as $group_key => $group_name){
            $options[] = ['value'=>$group_key,'label'=>$group_name];
        }

        if($add_title){
            array_unshift($options,['value'=>'','label'=>'分类组']);
        }

        return UtilHtml::formatHtmlOptions($options,'value','label','',$selected);
    }

    public function sortByLevel($catalogs,$except=''){
        if($catalogs instanceof Arrayable){
            $catalogs = $catalogs->toArray();
        }

        $catalogs_tree = UtilArr::listToTree($catalogs,'','parent_id','id','children');
        return  UtilArr::treeToList($catalogs_tree,'children',0,$except,'id');
    }


    public function buildCatalogsOptions($catalogs,$selected=[],$except='',$level_prefix='_',$add_top_level=false){

        $catalogs_list = $this->sortByLevel($catalogs,$except);
        $level_prefix = trim($level_prefix);

        $options = [];


        foreach ($catalogs_list as $catalog){
            $label = UtilArr::get($catalog,'name');
            $depth = intval(UtilArr::get($catalog,'depth'));
            if($level_prefix && $depth > 0){

                $label = str_pad('',$depth*2,$level_prefix) . $label;
            }
            $options[] = ['value'=>UtilArr::get($catalog,'id'),'label'=>$label];
        }

        if($add_top_level){
            $top_level_label = is_string($add_top_level) ? trim($add_top_level) : '顶级分类';
            array_unshift($options,['value'=>'','label'=>$top_level_label]);
        }

        return UtilHtml::formatHtmlOptions($options,'value','label','',$selected);
    }
}
